package com.example.martian.service;

import com.example.martian.config.util.RedisUtils;
import com.example.martian.mapper.IndexMapper;
import com.example.martian.mapper.RegisterMapper;
import com.example.martian.utils.*;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.util.*;
import java.util.regex.Pattern;
import static com.example.martian.utils.SmsSample.*;

@Service
@Transactional(readOnly = true)
public class RegisterService {

    @Autowired
    private RegisterMapper registerMapper;

    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    private FileUtil fileUtil;

    @Autowired
    private IndexMapper indexMapper;

    //注册
    @Transactional
    public Object registerPhoneOrEmail(String address, String password,String passwordrep,String invitationcode,String code) throws Exception {
        List<Integer> list = registerMapper.selectInvitationcode();
        String msg = "";
        String state = "";
        String result = "";
        String addressKey = "";
        String stringRandom = Utils.getRandom(6);
        String addressUID = Utils.getRandom(18);
        System.out.println(list);
        int countPerson = 0;
        Map<String,Object> mapObj = new HashMap<>();
        Map<String, Object> param = new HashMap<>();
        Pattern pattern = Pattern.compile("[0-9]*");
        Pattern pattern1 = Pattern.compile("^[0-9a-z]+\\w*@([0-9a-z]+\\.)+[0-9a-z]+$");
        boolean matche = pattern1.matcher(address).matches();
        boolean matches = pattern.matcher(address).matches();
        Pattern pass = Pattern.compile("([0-9a-zA-Z]){8,16}$");
        boolean matches1 = pass.matcher(password).matches();
        int num = registerMapper.selectAddress(address);
        if (num != 0) {
            return Utils.toJSON("该用户已注册，请登录", Utils.toJSONmap(), "1");
        }
        if (num == 0) {
            if ((address.length() == 11 && matches) || matche ) {
                param.put("address", address);
            } else {
                return Utils.toJSON("请输入正确的手机号码或邮箱格式", Utils.toJSONmap(), "2");
            }
            if (matches1) {
                param.put("password", password);
            } else {
                return Utils.toJSON("请输入正确的密码格式,密码不能包含特殊符号和空格且不小于8位", Utils.toJSONmap(), "3");
            }
            param.put("jymimaZt",0);
            param.put("invitationcode", stringRandom);
            param.put("zt", 0);
            param.put("person", 0);
            param.put("addressUid",addressUID);
            param.put("newAward",1000);
            param.put("inviteAward",0);
            Boolean aBoolean = verificationMessage(code, address);
            if (aBoolean == true){
                if (passwordrep.equals(password)){
                    int flg = registerMapper.insertAddressPhone(param);
                    if (flg > 0) {
                        result = param.get("id").toString();
                        msg = "注册成功";
                        state = "0";
                    }
                }else {
                    return Utils.toJSON("两次密码必须相同",Utils.toJSONmap(),"4");
                }
            }else{
                return Utils.toJSON("验证码错误,请核实后重新输入",Utils.toJSONmap(),"5");
            }
        }
        int flg = registerMapper.selectAccountByInvitationcodeCount(invitationcode);
        Integer userid = registerMapper.selectAccountByInvitationcode(invitationcode);
        if (flg != 0) {
            param.put("invitationcode", stringRandom);
            for (int i = 0;i < list.size();i++){
                System.out.println(list.get(i));
                if (Integer.parseInt(invitationcode)==list.get(i)) {
                    System.out.println(invitationcode.equals(list.get(i)));
                    Integer person = registerMapper.selectAccountPersonById(userid);
                    countPerson = person + 1;
                    Map<String, Object> objectMap = new HashMap<>();
                    objectMap.put("userid", userid);
                    objectMap.put("person", countPerson);
                    registerMapper.updatePerson(objectMap);
                    param.put("person", 0);
                    mapObj.put("address",address);
                    mapObj.put("rz_zt",0);
                    mapObj.put("account_id",param.get("id"));
                    mapObj.put("level","VIP1");
                    mapObj.put("direct_id",userid);
                    mapObj.put("direct_rebate","0");
                    mapObj.put("indirect_rebate","0");
                    registerMapper.insertUser(mapObj);
                    Integer integerId = registerMapper.selectDirect_id(userid);
                    if (integerId != null){
                        Integer integer = Integer.valueOf((Integer) param.get("id"));
                        registerMapper.updateIndirect_id(integerId,integer);
                    }
                }
            }
        }else {
                mapObj.put("address",address);
                mapObj.put("rz_zt",0);
                mapObj.put("account_id",param.get("id"));
                mapObj.put("level","VIP1");
                mapObj.put("direct_id",userid);
                registerMapper.insertUser(mapObj);
            }
        //添加钱包账户
        List<Map<String, Object>> maps = registerMapper.checkCoin();
        Map<String,Object> objectMap = new HashMap<>();
        for (Map<String,Object> map : maps){
            objectMap.put("address",address);
            objectMap.put("coin",map.get("cmc_coins"));
            objectMap.put("money","0.0000");
            objectMap.put("validMoney","0");
            objectMap.put("freezeMoney","0");
            com.alibaba.fastjson.JSONObject coinAddress = Custody.getCoinAddress(map.get("cmc_coins").toString());
            String success = coinAddress.get("success").toString();
            if (success.equals("false")){
                objectMap.put("addressKey","");
            }else {
                com.alibaba.fastjson.JSONObject resultCoin = coinAddress.getJSONObject("result");
                addressKey = resultCoin.get("address").toString();
                objectMap.put("addressKey",addressKey);
            }
            int countWallet = registerMapper.selectCountWallet(address);
            if (countWallet <= 5){
                registerMapper.insertAddressCoin(objectMap);
            }
        }
        //添加挖矿账户
        Map<String,Object> objectMapMing = new HashMap<>();
        Map<String,Object> mapMining = new HashMap<>();
        for (Map<String,Object> map : maps){
            objectMapMing.put("address",address);
            objectMapMing.put("coin",map.get("cmc_coins"));
            objectMapMing.put("money","0.0000");
            objectMapMing.put("validMoney","0");
            objectMapMing.put("freezeMoney","0");
            com.alibaba.fastjson.JSONObject coinAddress = Custody.getCoinAddress(map.get("cmc_coins").toString());
            String success = coinAddress.get("success").toString();
            if (success.equals("false")){
                objectMapMing.put("addressKey","");
            }else {
                com.alibaba.fastjson.JSONObject resultCoin = coinAddress.getJSONObject("result");
                addressKey = resultCoin.get("address").toString();
                objectMapMing.put("addressKey",addressKey);
                if (map.get("cmc_coins").toString().equals("BTC")){
                    mapMining.put("address",address);
                    mapMining.put("addressKey",addressKey);
                    mapMining.put("earnings","0.0000000");
                    mapMining.put("countEarnings","0.0000000");
                    mapMining.put("calidEarnings","0.0000000");
                    mapMining.put("type",1);
                    registerMapper.insertMiningEarnings(mapMining);
                }else if (map.get("cmc_coins").toString().equals("ETH")){
                    mapMining.put("address",address);
                    mapMining.put("addressKey",addressKey);
                    mapMining.put("earnings","0.0000000");
                    mapMining.put("countEarnings","0.0000000");
                    mapMining.put("calidEarnings","0.0000000");
                    mapMining.put("type",2);
                    registerMapper.insertMiningEarnings(mapMining);
                }else if (map.get("cmc_coins").toString().equals("FIL")){
                    mapMining.put("address",address);
                    mapMining.put("addressKey",addressKey);
                    mapMining.put("earnings","0.0000000");
                    mapMining.put("countEarnings","0.0000000");
                    mapMining.put("calidEarnings","0.0000000");
                    mapMining.put("type",3);
                    registerMapper.insertMiningEarnings(mapMining);
                }
            }
            int countWallet = registerMapper.selectCountWalletMinings(address);
            if (countWallet <= 5){
                registerMapper.insertAddressCoinMining(objectMapMing);
            }
        }

        return Utils.toJSON(msg, result, state);
    }

    //登录
    @Transactional
    public Object login(String address, String password,String token) {
        JSONArray jsonArray =  new JSONArray();
        String result = "";
        Map<String, Object> param = new HashMap<>();
        Map<String, Object> map = new HashMap<>();
        param.put("address", address);
        param.put("password", password);
        int num = registerMapper.checkLogpwdBuyId(param);
        if (num > 0) {
            List<Map<String, Object>> maps = registerMapper.getUserid(param);
            for (Map<String,Object> mapList : maps){
                map.put("userid", String.valueOf(mapList.get("userid")));
                map.put("address", address);
                map.put("addressUid",mapList.get("addressUid"));
                map.put("invitationcode",mapList.get("invitationcode"));
            }
            redisUtils.setDataToCache(address+token,token);
            jsonArray.add(map);
            result = jsonArray.toString();
        } else {
           return Utils.toJSON("请输入正确的用户名和密码",Utils.toJSONmap(),"1");
        }
        return Utils.toJSON("登录成功", result, "0");
    }

    //查询账户余额
    public Object selectAllCoinMoney(String address){
        JSONObject jsonObject = null;
        JSONArray jsonArray = new JSONArray();
        List<Map<String, Object>> mapList = indexMapper.selectAllCoinMoney(address);
        for (Map<String,Object> map : mapList){
            jsonObject = new JSONObject();
            jsonObject.put("address",map.get("cmc_address"));
            jsonObject.put("coin",map.get("cmc_coin"));
            jsonObject.put("money",map.get("cmc_money"));
            jsonArray.add(jsonObject);
        }
        return Utils.toJSON("访问成功",jsonArray.toString(),"0");
    }

    //快速登录
    @Transactional
    public Object celerityLogin(String address,String code){
        String result = "";
        Map<String, Object> param = new HashMap<>();
        param.put("address", address);
        int num = registerMapper.selectAddress(address);
        if (num > 0){
            Boolean aBoolean = verificationMessage(code,address);
            if (aBoolean){
                List<Map<String, Object>> maps = registerMapper.checkUserIdExists(address);
                for (Map<String,Object> mapList : maps) {
                    Map<String, Object> map = new HashMap<>();
                    map.put("userid", mapList.get("userid"));
                    map.put("address", address);
                    map.put("addressUid", mapList.get("addressUid"));
                    map.put("invitationcode",mapList.get("invitationcode"));
                    result = JSONObject.fromObject(map).toString();
                }

            }else {
                return Utils.toJSON("验证码错误，请核实后重新输入",Utils.toJSONmap(),"2");
            }
        }else {
            return Utils.toJSON("用户不存在，请注册",Utils.toJSONmap(),"1");
        }
        return Utils.toJSON("登录成功",result,"0");
    }

    //找回密码
    @Transactional(readOnly = false)
    public Object forgetPass(String address,String password,String passwordrep){
        Map<String, Object> param = new HashMap<>();
        param.put("address", address);
        int num = registerMapper.selectAddress(address);
        if (num > 0){
            if (password.equals(passwordrep)){
                registerMapper.forgetPass(address, password);
            }else {
                return Utils.toJSON("两次密码必须相同",Utils.toJSONmap(),"3");
            }
        }else {
            return Utils.toJSON("用户不存在，请注册",Utils.toJSONmap(),"1");
        }
        return Utils.toJSON("重置成功",Utils.toJSONmap(),"0");
    }

    //设置交易密码
    @Transactional
    public Object addJYpassword(Integer userId, String jypassword, String jypasswordrep,String code) {
        String msg = "设置失败";
        String result = "";
        String state = "1";
        String address = registerMapper.selectAccountAddressById(userId);
        Boolean aBoolean = verificationMessage(code,address);
        if (aBoolean){
            if (jypassword.length() == 6) {
                if (jypassword.equals(jypasswordrep)) {
                    registerMapper.jyPassword(userId, jypassword);
                    registerMapper.updateJymimaZt(1,userId);
                    msg = "设置成功";
                    state = "0";
                } else {
                    msg = "两次密码不正确，请重新输入";
                    state = "1";
                }
            } else {
                return Utils.toJSON("密码长度不小于6位，且是数字", Utils.toJSONmap(), "2");
            }
        }else {
            return Utils.toJSON("验证码错误，请核实后重新输入",Utils.toJSONmap(),"3");
        }

        return Utils.toJSON(msg, Utils.toJSONmap(), state);
    }

    // 修改昵称或者头像
    @Transactional
    public String updateNickName(MultipartFile img, String nickname, String userid) {
        String msg = "";
        String state = "";
        Map<String, Object> param = new HashMap<>();
        try {
            String url = null;
            if (img == null || img.getSize() == 0) {
            } else {
                byte[] buffer = new byte[0];
                try {
                    buffer = img.getBytes();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                url = fileUtil.saveFile("image", userid, buffer);
                System.out.println(url);
                param.put("icon",url);
            }
            if (nickname != null && !"".equals(nickname)) {
                param.put("nickname", nickname);
            }
            param.put("userid",userid);
            int isflag = registerMapper.updateNickName(param);
            if (isflag > 0){
                msg = "修改成功";
                state = "0";
            }else {
                msg = "修改失败";
                state = "1";
            }

        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException();
        }
        return Utils.toJSON(msg, Utils.toJSONmap(), state);
    }

    //修改登录密码
    @Transactional
    public Object updateLoginPassword(Integer userId, String oldpassword, String password, String passwordrep) {
        Map<String, Object> param = new HashMap<>();
        Pattern pattern = Pattern.compile("([0-9a-zA-Z]){8,16}$");
        boolean matches = pattern.matcher(password).matches();
        System.out.println(matches);
        try {
            int num = registerMapper.selectById(userId);
            if (num > 0) {
                String oldpass = registerMapper.selectAccountById(userId);
                System.out.println(oldpass);
                if (oldpass.equals(oldpassword)) {
                    if (!matches) {
                        return Utils.toJSON("请输入正确的密码格式,密码不小于8位", null, "2");
                    } else {
                        if (oldpassword.equals(password)) {
                            return Utils.toJSON("新密码和原密码一致，请重新输入", null, "5");
                        }
                        param.put("userId", userId);
                        param.put("password", password);
                        if (password.equals(passwordrep)) {
                            registerMapper.updatePassword(param);
                        } else {
                            return Utils.toJSON("两次密码输入不正确，请重新输入", null, "3");
                        }

                    }
                } else {
                    return Utils.toJSON("原密码不正确，请重新输入", null, "1");
                }
            } else {
                return Utils.toJSON("参数错误", "500", "4");
            }
        } catch (Exception e) {
            e.getStackTrace();
        }

        return Utils.toJSON("修改成功", null, "0");
    }



    //邀请页面
    public Object invitation(Integer userId){
        Integer person = registerMapper.selectAccountPersonById(userId);
        String invitationcode = registerMapper.selectInvitationcodeById(userId);
        int buyCount = registerMapper.selectBuyCount(userId);
        String inviteAward = registerMapper.selectInviteAward(userId);
        Map<String,Object> map = new HashMap<>();
        map.put("person",person);
        map.put("invitationCode",invitationcode);
        map.put("buy_number",buyCount);
        map.put("reward",inviteAward);
        return Utils.toJSON("访问成功",map.toString(),"1");
    }

    //查询昵称和头像
    public Object selectNikeNameAndPhoto(Integer userId){
        JSONArray jsonArray = new JSONArray();
        JSONObject jsonObject = new JSONObject();
        List<Map<String, Object>> mapList = registerMapper.selectNikeNameAndPhoto(userId);
        for (Map<String,Object> map : mapList){
            jsonObject.put("nickName",map.get("cmc_nickname"));
            jsonObject.put("icon",map.get("cmc_icon"));
            jsonArray.add(jsonObject);
        }
        return Utils.toJSON("访问成功",jsonArray.toString(),"0");
    }

    //版本更新
    @Transactional
    public String appUpdateInfomation() {
        String msg = "加载失败";
        String state = "1";
        String result = "";
        String uuid = StringUtil.getRandom(11);
//        redisUtils.setDataToCache("uuid",uuid);
        try {
            JSONObject map = new JSONObject();
            // 获取缓存
//            Object cresult = cacheService.cacheResult("appversion_" + type);
//            if (cresult != null) {
//                map = JSONObject.fromObject(cresult);
//            } else {
            Map<String, Object> params = new HashMap<>();
            map = JSONObject.fromObject(registerMapper.appUpdateInfomation());
            System.out.println(map);
            //过期时间24小时
            redisUtils.setDataToCache("appversion_" + uuid, uuid, 60 * 60 * 24);
//            }
            JSONObject mapJson = new JSONObject();
            //处理
            System.out.println(map.toString());
//            String versionapp = map.get("version").toString();
//            String zt = map.get("constrainte").toString();
            mapJson.put("constrainte", map.get("constrainte"));
            mapJson.put("version_link", map.get("link"));
            mapJson.put("version_text", map.get("text"));
            mapJson.put("version", map.get("version"));
            mapJson.put("platinum", map.get("platinum"));
            mapJson.put("iphone_link", map.get("iphone_link"));
            mapJson.put("image", map.get("image"));
            result = JSONObject.fromObject(mapJson).toString();
            msg = "加载成功";
            state = "0";
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException();
        }
        return Utils.toJSON(msg, result, state);
    }

    //发送验证码
    @Transactional
    public Object sendSmsSendMessage(String address){
        Pattern pattern = Pattern.compile("[0-9]*");
        boolean matches = pattern.matcher(address).matches();
        String result = "";
        String code = Utils.getRandom(6);
        if (matches){
            String testUsername = "garycloud"; //在短信宝注册的用户名
            String testPassword = "QAZmlp"; //在短信宝注册的密码
            String testPhone = address;
            int time = 5;
            String testContent = "【灰度云矿】您的验证码是"+code+"，在"+time+"分钟内有效。若非本人操作请忽略此消息。"; // 注意测试时，也请带上公司简称或网站签名，发送正规内容短信。千万不要发送无意义的内容：例如 测一下、您好。否则可能会收不到
            String httpUrl = "http://api.smsbao.com/sms";
            StringBuffer httpArg = new StringBuffer();
            httpArg.append("u=").append(testUsername).append("&");
            httpArg.append("p=").append(md5(testPassword)).append("&");
            httpArg.append("m=").append(testPhone).append("&");
            httpArg.append("c=").append(encodeUrlString(testContent, "UTF-8"));
            result = request(httpUrl, httpArg.toString());
        } else {
            NewSendEmail.MailUtils mailUtils = new NewSendEmail.MailUtils(address, code);
            mailUtils.run();
            result = Utils.toJSONmap();
        }
        redisUtils.setDataToCache("registerCode"+address,code,30000);
        return Utils.toJSON("发送成功",result,"0");
    }

    //校验验证码
    public Boolean verificationMessage(String code,String address){
        Object uuid = redisUtils.getDataFromCache("registerCode" + address);
        Boolean boole = code.equals(uuid);
        if (boole){
            Timer timer = new Timer();
            TimerTask task = new TimerTask() {
                public void run() {
                    redisUtils.clearCache("registerCode"+address);
                }
            };
            timer.schedule(task, 5 * 60 * 1000);
        }
        return boole;
    }

    //查询交易密码状态
    public Object checkJymimaZt(Integer userId){
        Integer jymimaZt = registerMapper.checkJymimaZt(userId);
        System.out.println(jymimaZt);
        return Utils.toJSON("查询成功",jymimaZt.toString(),"0");
    }

    //查询优惠券
    public Object selectNewAward(Integer userId){
        JSONArray jsonArray = new JSONArray();
        JSONObject jsonObject = new JSONObject();
        String newAward = registerMapper.selectNewAward(userId);
        if (newAward.equals("0")){
            jsonObject.put("name","新用户体验券");
            jsonObject.put("newAward",newAward);
            jsonArray.add(jsonObject);
            return Utils.toJSON("查询成功",jsonArray.toString(),"0");
        }
        jsonObject.put("name","新用户体验券");
        jsonObject.put("newAward",newAward);
        jsonArray.add(jsonObject);
        return Utils.toJSON("查询成功",jsonArray.toString(),"0");
    }
}
